package com.aote.expression.paramprocessor;

import java.util.Iterator;
import java.util.Map;

import org.w3c.dom.Element;

import com.aote.expression.Param;
import com.aote.model.DataShowTableModel;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLBasicModel;
import com.browsesoft.user.User;

public class SumAmountProcessor implements ParamProcessor {
	/**
	 * 在页面配置表达式
	 */
	public String process(Param param, Map attribures, User loginUser,
			HTMLBasicComponent component) throws NoFitValueException {
		double coldnum = 0;
		Map map = param.getParams();
		String name = (String) map.get("tablename");
		String col = (String) map.get("colname");
		// 根据基础组件得到子组件，根据子组件得到元素
		Iterator iter = component.getChildrenComponents();
		while (iter.hasNext()) {
			HTMLBasicComponent basic = (HTMLBasicComponent) iter.next();
			Element element = basic.getElement();
			String ename = element.getAttribute("tablename");
			// 取得表名
			if (ename.equals(name)) {
				HTMLBasicModel model = basic.getModel();
				if (model instanceof DataShowTableModel) {
					DataShowTableModel datamodel = (DataShowTableModel) model;
					String coldata = null;
					// 根据是否只计算选中行，调用不同方法
					String selected = (String) map.get("selected");
					if (selected != null) {
						// 根据计算方式，调用不同的计算过程
						String computer = (String)map.get("computer");
						// 默认为求和
						if(computer == null) {
							coldata = datamodel.getSumOfSelected(col);
						} else if(computer.equals("max")) {
							coldata = datamodel.getMaxOfSelected(col);
						} else if(computer.equals("min")) {
							coldata = datamodel.getMinOfSelected(col);
						} else {
							throw new RuntimeException("未知计算方法：" + computer);
						}
					} else {
						coldata = datamodel.getDataByColumnName(col);
					}
					double coldnumber = Double.parseDouble(coldata);
					coldnum = coldnumber;
					break;
				}
			}
		}
		return Double.toString(coldnum);
	}
}
